package custom

import (
	"iot-base/common/dbconn"
	"iot-base/common/webapi"

	"github.com/gin-gonic/gin"
	"gorm.io/datatypes"
	"gorm.io/gorm"
)

type CustomParam struct {
	dbconn.OBJObjIID
	CType string         `gorm:"type:varchar(40);uniqueIndex:custom_param_index" json:"c_type"`
	SName string         `gorm:"type:varchar(40);uniqueIndex:custom_param_index" json:"s_name"`
	Body  datatypes.JSON `json:"body"`
}

func init() {
	dbconn.DBConnection.AutoMigrate(&CustomParam{})
}
func InitAPI(r *gin.RouterGroup) {
	custom := r.Group("custom")
	{
		custom.GET("/:ctype/:sname", func(c *gin.Context) {
			ctype := c.Param("ctype")
			sname := c.Param("sname")
			var items []CustomParam
			tx := dbconn.DBConnection.Model(&CustomParam{})
			if ctype != "" && ctype != "ALL" {
				tx.Where("c_type=?", ctype)
			}
			if sname != "" && sname != "ALL" {
				tx.Where("s_name=?", sname)
			}
			err := tx.Find(&items).Error
			webapi.SendResult(items, err, c)
		})
		custom.PUT("/", func(c *gin.Context) {
			var tobj CustomParam
			errJson := c.ShouldBind(&tobj)
			if errJson != nil {
				webapi.SendError(errJson.Error(), webapi.ParamsError, c)
			} else {
				err := dbconn.DBConnection.Transaction(func(tx *gorm.DB) error {
					//var count = 0
					var uid int64
					err := tx.Model(&CustomParam{}).Where("c_type=? and s_name=?", tobj.CType, tobj.SName).Select("uid").First(&uid).Error
					if err != nil {
						tobj.UID = 0
						return tx.Create(&tobj).Error
					} else {
						tobj.UID = uid
						return tx.Save(&tobj).Error
					}
				})
				if err == nil {
					webapi.SendOK(c)
				} else {
					webapi.SendError(err.Error(), webapi.DBError, c)
				}
			}
		})
	}

}
